package com.example.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import com.example.tool.ReadBigExecl;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
//import org.springframework.boot.configurationprocessor.json.JSONException;
//import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;

@Controller
@RequestMapping("file")
@Slf4j
public class FileController {
    @Value("${file.upload.dir}")
    private String uploadFilePath;

    @GetMapping(value = {"", "/", "/index"})
    public String index() {
        return "upload";
    }

    @ResponseBody
    @PostMapping("/uploadFile")
    public String fileUpload(@RequestParam("file") MultipartFile file) throws Exception {
        JSONObject result = new JSONObject();
        if (file.isEmpty()) {
            result.set("error", "空文件!");
            return result.toString();
        }
        // 文件名
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("上传文件名称为:{}, 后缀名为:{}!", fileName, suffixName);

//        System.out.println(suffixName);
        if (!suffixName.equals(".xlsx")){
            result.set("error", "请上传后缀为xlsx的文件!");
            return result.toString();
        }
        //删除文件
        new File(uploadFilePath + '/'+"b.xlsx").delete();
        new File(uploadFilePath + '/'+"a.xlsx").delete();

        File fileTempObj = new File(uploadFilePath + "/" + "a.xlsx");
        // 检测目录是否存在
        if (!fileTempObj.getParentFile().exists()) {
            fileTempObj.getParentFile().mkdirs();
        }

        try {
            FileUtil.writeBytes(file.getBytes(), fileTempObj);
        } catch (Exception e) {
            log.error("发生错误: {}", e);
            result.set("error", e.getMessage());
            return result.toString();
        }
        //处理文件名
        File source=new File(uploadFilePath+"/"+"a.xlsx");
        result.set("success", "文件上传成功,请返回并等待文件比较成功后，下载!");
        File dest=new File(uploadFilePath+"/"+"b.xlsx");
        Files.copy(source.toPath(), dest.toPath());
        ReadBigExecl.storage(dest);

        return result.toString();
    }

    // 下载到了默认的位置
    @ResponseBody
    @GetMapping("/downloadFile")
    public String fileDownload(HttpServletResponse response, @RequestParam("fileName") String fileName) throws IOException {
        JSONObject result = new JSONObject();

        File file = new File(uploadFilePath + '/' + fileName);
        if (!file.exists()) {
            result.set("error", "下载文件不存在!");
            return result.toString();
        }

        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        byte[] readBytes = FileUtil.readBytes(file);
        OutputStream os = response.getOutputStream();
        os.write(readBytes);

        result.set("success", "下载成功!");

        return result.toString();
    }


}
